/*********************************************************
*Copyright (c) 2009 Rob Groves. All Rights in Pw 
*@des: 对Mysql操作库 简单封装
*@name: DbQuery.cpp
*@author: zhognsx
*@time: 2015-02-03
*********************************************************/

#include "DbQuery.h"
#include "QueryResult.h"

DBQuery::DBQuery()
{
	stat = 0;
	m_szErrMsg = "";

}

DBQuery::~DBQuery()
{

}

string DBQuery::GetErrMsg()
{
	return m_szErrMsg;
}

int DBQuery::Init()
{
	if (stat == 0) {
		mysql_init(&link); 
        stat = 1; //初始化连接    
	}
	return 0;
}

int  DBQuery::Connet()
{
	Close();
	// mysql_real_connect(MYSQL *mysql, const char *host,
	// 	const char *user, const char *passwd, const char *db,
	// 	 unsigned int port, const char *unix_socket, unsigned int client_flag);
	Init();

	#if MYSQL_VERSION_ID >= 50013
	my_bool reconnect = 1;

	if (mysql_options(&link, MYSQL_OPT_RECONNECT, &reconnect) != 0){
		MYSQL_WAR_ERROR("MYSQL_OPT_RECONNECT Set Error! ERROR:", mysql_error(&link))
		return EMYSQLErrDBInit;
	}

	if (mysql_options(&link, MYSQL_SET_CHARSET_NAME, "utf8") != 0){
		MYSQL_WAR_ERROR("MYSQL_OPT_RECONNECT Set Error! ERROR:", mysql_error(&link))
		return EMYSQLErrDBInit;
	}

	#endif
	//
	if (!mysql_real_connect(&link, _ip.c_str(), _user.c_str(), _pwd.c_str(), 
								_dbName.c_str(), _port,  NULL, CLIENT_MULTI_STATEMENTS) ) {
		MYSQL_WAR_ERROR("Unable to connect to server Error:", mysql_error(&link))
		return EMYSQLErrDBConn;
    }
	//mysql_set_character_set(&link, "gbk");
    // //关闭事务自动提交
    // if (mysql_autocommit(&link, 0) != 0){
    // 	MYSQL_WAR_ERROR("Unable to set autocommit Close. Error:", mysql_error(&link))
    // 	return EMYSQLErrDBInit;
    // }

	stat = 2; //连接成功

	return EMYSQLSuc;
}

void DBQuery::SetConnetInfo(const string &host, uint16_t port, const string &user, 
						const string &pwd, const string &dbName)
{
	_ip = host;
	_port = port;
	_user = user;
	_pwd = pwd;
	_dbName = dbName;
}

int DBQuery::ExecuteNonQuery(const string &sql)
{	
	if (stat != 2) return EMYSQLErrDBInit;
	int ret = mysql_real_query(&link, sql.c_str(), sql.length());
	if (ret != 0 ) 
	{
		string msg = "";
		msg += mysql_error(&link);
		msg += " SQL: ";
		msg += sql;
		MYSQL_WAR_ERROR("Query Error:", msg);
		return EMYSQLErrDBExe;
	}

	return EMYSQLSuc;
}


int DBQuery::ExecuteResult(const string &sql, boost::shared_ptr<QueryResult> qres)
{	
	int ret = ExecuteNonQuery(sql);
	if( ret < 0){
		return ret;
	}

	MYSQL_RES *res;
	res = mysql_store_result(&link);
   	if (!res) {
       MYSQL_WAR_ERROR("Get Store Result Error: ", mysql_error(&link))
       return EMYSQLErrDBExe;
    }
    qres->SetRes(res);
    
    return EMYSQLSuc;
}

int DBQuery::Close()
{
	if (stat == 2){
		mysql_close(&link);
		stat = 0;
	}
	return 0;
}

int DBQuery::GetInsertId()
{
	return mysql_insert_id(&link);
}

int DBQuery::GetAffectedRows()
{
	return mysql_affected_rows(&link);
}

int DBQuery::GetStat()
{
	return stat;
}